<?php
namespace Admin\Model;
use Think\Model;
class GoodsModel extends Model 
{
	// 设置添加时表单中允许接收的字段【安全】
	protected $insertFields = 'goods_name,shop_price,goods_desc,is_on_sale,cat_id,is_floor';
	// 设置修改的表单中允许出现的字段
		
	// 定义表单验证的规则
		protected $_validate = array(
			array('goods_desc', 'require', '请填写商品描述', 1),
			array('goods_name', 'require', '商品名称不能为空！', 1),
			array('shop_price', 'currency', '市场价格必须是货币类型！', 1),
			
		);
  
	//使用钩子函数   
	//TP在使用add 方法前会先执行这个钩子函数  _before_insert
	protected function _before_insert(&$data,$option){
		  $data['goods_desc'] = removeXSS($_POST['goods_desc']);
				$data['addtime'] = time();
		//上传图片
		if($_FILES['logo'] && $_FILES['logo']['error']==0){
			$config = array(
			    'maxSize'    =>    3145728,
			    'rootPath'   =>    './Public/Uploads/',
			    'savePath'   =>    'Goods',
			    'exts'       =>    array('jpg', 'gif', 'png', 'jpeg'),
			    
			);
			$upload = new \Think\Upload($config);// 实例化上传类
			//调用upload方法;
			$info = $upload->upload();
			//echo '<pre>';
			//var_dump($info);die();
			if(!$info) {// 上传错误提示错误信息
				$this->error($upload->getError());
				return  false;
			}else{
				//echo '<pre>';
				//var_dump($info['logo']);die();
				//var_dump($info['logo']['savepath']);die();
				//拼接图片的路径
				$logo = $info['logo']['savepath'] . $info['logo']['savename'];
				$sm_logo = $info['logo']['savepath'] . 'sm_' . $info['logo']['savename'];
				$mid_logo = $info['logo']['savepath'] . 'mid_' . $info['logo']['savename'];
				//生成缩略图
				//实例化这个类库
				$image = new \Think\Image();
				//打开原图
				$image->open('./Public/Uploads/'.$logo);
				// 生成一个缩放后填充大小150*150的缩略图并保存为thumb.jpg
				$image->thumb(150, 150,1)->save('./Public/Uploads/'.$sm_logo);
				$image->thumb(650, 650,1)->save('./Public/Uploads/'.$mid_logo);
				//把路径 保存在商品表中
				$data['logo'] = $logo;
				$data['sm_logo'] = $sm_logo;
				$data['mid_logo'] = $mid_logo;		
			}
		}
	}
	//删除之前执行的钩子函数 下面的代码也就是删除之前把硬盘里面的图片给删除了
	public function _before_delete($data,$option){
		//先从控制器中取出这件商品
		 $goodsModel = D('Goods');
		 $info = $goodsModel->field('logo','mid_logo','sm_logo')->find($data['id']);
		// echo '<pre>';
		 //var_dump($info);die();
		 if($info){
			 unlink('./Public/Uploads/'.$info['logo']);
			 unlink('./Public/Uploads/'.$info['mid_logo']);
			 unlink('./Public/Uploads/'.$info['sm_logo']);	
		 }
		 /*******************删除会员价格***********************/
		 $id = I('get.id');
		// var_dump($id);die();
		 $mprice = D('member_price');
		 $mprice->where(array(
		 		'goods_id'=>array('eq',$id),
		 ))->delete();
	}
	//修改之前需要  (图片的修改)
	public function _before_update(&$data,$option){
		 /***************会员价格的修改************/
		$mprice1 = I('post.member_price');
		$level_id = I('post.level_id');
		//var_dump($level_id);die();
		$id = I('get.id');
		//var_dump($id);die();
		// var_dump($id);die();
		$mprice = D('member_price');
		$mprice->where(array(
				'goods_id'=>array('eq',$id),
		))->delete();
		if(mprice1){
			foreach($mprice1 as $k=>$v){
				   $mprice->add(array(
					'level_id'=>$level_id[$k],
	            	'price'   =>$v,
					'goods_id'=>$id,
				)); 
			}
		}  
		
		if(isset($_FILES['logo']) && $_FILES['logo']['error']==0){
			$config = array(
					'maxSize'    =>    3145728,
					'rootPath'   =>    './Public/Uploads/',
					'savePath'   =>    'Goods',
					'exts'       =>    array('jpg', 'gif', 'png', 'jpeg'),
					 
			);
			$upload = new \Think\Upload($config);// 实例化上传类
			//调用upload方法;
			$info = $upload->upload();
			
			if(!$info) {// 上传错误提示错误信息
				$this->error($upload->getError());
				return  false;
			}else{
				//echo '<pre>';
				//var_dump($info['logo']);die();
				//var_dump($info['logo']['savepath']);die();
				//拼接图片的路径
				$logo = $info['logo']['savepath'] . $info['logo']['savename'];
				$sm_logo = $info['logo']['savepath'] . 'sm_' . $info['logo']['savename'];
				$mid_logo = $info['logo']['savepath'] . 'mid_' . $info['logo']['savename'];
				//生成缩略图
				//实例化这个类库
				$image = new \Think\Image();
				//打开原图
				$image->open('./Public/Uploads/'.$logo);
				// 生成一个缩放后填充大小150*150的缩略图并保存为thumb.jpg
				$image->thumb(150, 150,1)->save('./Public/Uploads/'.$sm_logo);
				$image->thumb(650, 650,1)->save('./Public/Uploads/'.$mid_logo);
				//把路径 保存在商品表中
				$data['logo'] = $logo;
				$data['sm_logo'] = $sm_logo;
				$data['mid_logo'] = $mid_logo;
				//删除原来的数据
			   //接收商品的ID
			   $id = I('get.id');
				$info = $this->field('logo','mid_logo','sm_logo')->find($id);
				if($info){
					unlink('./Public/Uploads/'.$info['logo']);
					unlink('./Public/Uploads/'.$info['mid_logo']);
					unlink('./Public/Uploads/'.$info['sm_logo']);
				}
			}
		}
		
	}
	/***************计算商品价格***********************/
	public function _after_insert($data,$option){
		
		$mprice = I('post.member_price');
		//var_dump($mprice);die();
		$levelid = I('post.level_id');
		if($mprice){
			$mpmodel = D('member_price');
			foreach ($mprice as $k=>$v){
				$mpmodel->add(array(
					'goods_id'=>$data['id'],
					'level_id'=>$levelid[$k],
					'price'  =>$v,
				));
			}
		}
	}
	
	/*
	 * 翻页   搜索 和排序
	 */
	public function search(){


		/*************** 搜索 ******************/
		$where = array();  // 空的where条件
		$goodsModel = D('Goods');
		// 商品名称
		// var_dump($_GET);
		$gn = I('get.gn');
		if($gn){
			$where['a.goods_name'] = array('like', "%$gn%"); 
		} 
			
		// 价格
		$fp = I('get.fp');
		$tp = I('get.tp');
		if($fp && $tp)
			$where['a.shop_price'] = array('between', array($fp, $tp)); // WHERE shop_price BETWEEN $fp AND $tp
		elseif ($fp)
			$where['a.shop_price'] = array('egt', $fp);   // WHERE shop_price >= $fp
		elseif ($tp)
			$where['a.shop_price'] = array('elt', $tp);   // WHERE shop_price <= $fp
		

		//记录总条目数量
		// $count = $this->where($where)->count();
		$count = $goodsModel->alias('a')->field('a.*,b.cat_name')
		                   ->join('left join s50_category b on a.cat_id=b.id')
							->where($where)
		                   ->count();
		// var_dump($count);                

		//实例化对象
		$Page  = new \Think\Page($count,5);
		//显示上一页  下一页的字符串
		$Page->setConfig('next','下一页');
		$Page->setConfig('prev','上一页');
		$Page->setConfig('first', '首页');
		$Page->setConfig('last', '尾页');
		$show = $Page->show();
		// echo $show;
		//取得某一页的数据
		
		$info = $goodsModel->alias('a')->field('a.*,b.cat_name')
		                   ->join('left join s50_category b on a.cat_id=b.id')
		                   ->where($where)
		                   ->limit($Page->firstRow.','.$Page->listRows)->select();
		// var_dump($info);
		// $list = $this->where($where)->limit($Page->firstRow.','.$Page->listRows)->select();
		return array(
			'info'=> $info,
			'show'=> $show,
			'count'=> $count,


		);
	}
	//首页中间部分商品列表函数
	public function getGoods($limit=13){
		$data = $this->field('id,goods_name,shop_price,sm_logo')->limit($limit)->select();
		return $data;
	}
	//取得分类下面的所有商品
	public function getGoodsByCatId($catId,$limit){
		$catModel = D('Admin/Category');
		//取得其子分类的ID
		$children = $catModel->getChildren($catId);
		$children[] = $catId;
		$children = implode(',',$children);
		$where = array(array(
			'is_floor'  =>'是',
			'is_on_sale'=>'是',
			'cat_id'    =>array('in',$children),
		));
		return $this->field('id,shop_price,goods_name,sm_logo')->where($where)->limit($limit)->select();
		//var_dump($children);die();
	}

	
	//使用一个函数来计算会员价格
	public function getMemberPrice($goodsId){
		//取得商品最初设定的价格
		$goodsData = $this->field('shop_price')->find($goodsId);
		//取得会员价格   如果没有设定会员价格 则利用会员的级别乘以折扣率
		//先取得会员处于哪一个级别
		$id = session('member_id');
		//echo $id;die();
		if($id){
			//通过会员ID取出会员的jyz
			$memberModel = D('member');
			$jyz = $memberModel->field('jyz')->where(array(
				'id'=>$id,
			))->find();
			//var_dump($jyz);die();
			//通过jyz  获得会员的级别
			$mlModel = D('member_level');
			$mlData = $mlModel->field('id,level_name,level_rate')->where(array(
				'jifen_buttom'=>array('elt',$jyz['jyz']),
				'jifen_top'   =>array('egt',$jyz['jyz']),
			))->find();
			//var_dump($mlData);die();
			$mpModel = D('member_price');
			$mprice = $mpModel->field('price')->where(array(
			    'goods_id'=>array('eq',$goodsId),
				'level_id'=>array('eq',$mlData['id']),
			))->find();
			//var_dump($mprice);die();
			//如果为商品设定了会员价格的话
			if($mprice){
				$price = $mprice['price'];
			}else{
				$price = $goodsData['shop_price']*$mlData['level_rate']/100;
			}
			
		}else{
			$goodsModel = D('goods');
			$price = $goodsModel->field('shop_price')->where(array(
					'id'=>$goodsId,
			))->find();
			$price = $price['shop_price'];
			//var_dump($price);die();
		}
		return $price;
	}

	
}

